package com.yyq.sos.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.yyq.adms.cgjj.pojo.ReportIntroduce;
import com.yyq.adms.sysmanage.pojo.Accessory;
import com.yyq.adms.sysmanage.pojo.DataDictionary;
import com.yyq.adms.sysmanage.pojo.ExcelBean;
import com.yyq.adms.sysmanage.pojo.MethodBean;
import com.yyq.adms.usermanage.pojo.RecordSentDep;
import com.yyq.adms.util.JxlsUtil;
import com.yyq.adms.util.JxlsVo;
import com.yyq.adms.util.ValidateUtil;
import com.yyq.adms.util.ValidateVo;
import com.yyq.adms.yyb.advance.pojo.STApply;
import com.yyq.adms.yyb.advance.pojo.STPaper;
import com.yyq.adms.yyb.advance.pojo.STReport;
import com.yyq.adms.yyb.paper.pojo.PublishPaper;
import com.yyq.adms.yyb.summary.pojo.TechnologyApply;
import com.yyq.adms.yyb.summary.pojo.TechnologyPaper;
import com.yyq.adms.yyb.summary.pojo.TechnologyReport;
import com.yyq.adms.zz.pojo.Writings;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.service.BaseBpo;
import com.yyq.sos.util.DateUtil;
import com.yyq.sos.util.ObjectUtil;
import com.yyq.sos.util.PermissionsUtil;
import com.yyq.sos.util.SysModulesUtil;
import com.yyq.sos.util.SysParametersUtil;
import com.yyq.sos.util.filedownload.FileDownloadHandle;
import com.yyq.sos.util.fileupload.FileBean;
import com.yyq.sos.util.fileupload.FileUploadHandle;
import com.yyq.sos.util.page.PageForm;
import com.yyq.sos.util.page.PageFormData;


public class BaseAction extends ActionSupport
{
	private static final long serialVersionUID = 1291522531722539973L;
	protected static Log log = LogFactory.getLog(BaseAction.class);
	private String msg;
	private String processId;
	private String moduleName;
	private Object obj;
	private BaseBpo  bpo;
	private PageFormData formData;  //包含页面数据和翻页信息
	private List data;          //页面需要显示的数据
	private PageForm pageForm = new PageForm();  // 页面翻页，页码等信息
	private Map formMap = new HashMap();
	private String cmd;
	private String totalSize;
	private String pagePosition;
	
	private File accessory;
	private File addaccessory;
	private String accessoryFileName;
	private String accessoryContentType;
	
	public File getAddaccessory() {
		return addaccessory;
	}

	public void setAddaccessory(File addaccessory) {
		this.addaccessory = addaccessory;
	}

	// 是否需要添加父ID属性，目前仅有华南港工需要
	private boolean isNeedBatchAddParent;
	
	public boolean isNeedBatchAddParent() {
		return isNeedBatchAddParent;
	}

	public void setNeedBatchAddParent(boolean isNeedBatchAddParent) {
		this.isNeedBatchAddParent = isNeedBatchAddParent;
	}

	public String getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(String totalSize) {
		this.totalSize = totalSize;
	}

	public String getModuleName(String path){
		Object o = this.getFormValue("moduleName");
		if(o != null){
			String value = ((String[])o)[0];
			if(!value.trim().equals(""))
				return ((String[])o)[0];
		}
		return SysModulesUtil.getInstance().getModuleName(path);
	}
	
	/**
	 * 是否有权限
	 * @return
	 */
	private boolean hasPermisssion(LoginUser user,String path)
	{	
		String perms = (String)this.getRequest().getSession().getServletContext().getAttribute("permission");
		if(perms!=null && !perms.toUpperCase().equals("TRUE"))
			return true;
		String moduleId = getModuleName(path);
		System.out.println("moduleId:  "+moduleId);
		if(this.getRequest().getRequestURI().indexOf("modules.action")>0&& cmd!=null && cmd.equals("menu")){
			return true;
		}else if(this.getRequest().getRequestURI().indexOf("login.action")>0 && cmd!=null && cmd.equals("login")){
			return true;
		}else if(this.getRequest().getRequestURI().indexOf("login.action")<0){
			if(user!=null && user.getUserId().longValue()!=1)
				return user.hasRight(moduleId, cmd);
			else
				return true;
		} else
			return true;
	}
	
	/**
	 * 取得Session中保存的用户对象
	 * @return
	 */
	private LoginUser getLoginUser(){
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		LoginUser.userThread.set(user);
		return user;
	}
	public String execute() throws Exception
	{
		System.out.println("\n\n\n");
		System.out.println(DateUtil.formatDate(new Date(),DateUtil.FORMAT_DATETIME)+":   execute begin **********************************************************************");
		System.out.println("Action -------------->"+this.getClass().getName());
		System.out.println(" cmd命令字 -------------->"+this.getCmd());
		String[] typeArr = ((String[])this.getFormValue("type"));
		String type = (typeArr!=null&&typeArr.length>0)?typeArr[0]:null;
		System.out.println("  formMap.type-------------->" +type);
		String path = this.getRequest().getRequestURI();
		System.out.println("uri="+path);
		LoginUser user = getLoginUser(); 
		
		
		Integer pageSize = (Integer)this.getRequest().getSession().getAttribute("pageSize");
		if(pageSize!=null&&this.getPageForm().getPageSize()!=pageSize&&(!this.getCmd().equals(ActionType.ACTION_CHANGE))){
			this.getPageForm().setPageSize(pageSize);
		}
System.out.println("PAGE_TOOL_POSITION====>"+SysParametersUtil.getInstance().getValue("PAGE_TOOL_POSITION"));
		this.setPagePosition(SysParametersUtil.getInstance().getValue("PAGE_TOOL_POSITION"));
		
		/*if(!hasPermisssion(user,path)){
			//***********************************************************************************************
			//客户访问没权限跟踪
//			SysModules sysMSub=null;
//			SysModules sysMPar=null;
//			try{
//				String moduleId=this.getModuleId(path);
//				BaseBpo bpo_temp=BpoFactory.getSysModulesBpo(SysModules.class);
//				sysMSub=SysModulesUtil.getInstance().getContent(moduleId);
//				List list_temp=bpo.search("from "+SysModules.class.getName()+" where moduleId='"+sysMSub.getParentId()+"'");
//				sysMPar=(SysModules)list_temp.get(0);
//				this.setMsg("        You have no rights to access !\n-->module:"+sysMPar.getModuleName()+" -->menu:"+sysMSub.getModuleName()+"-->operation:"+this.getCmd());
//				System.out.println("no rights **********************************************************************");
//			}catch(Exception e){
//				e.printStackTrace();
//				this.setMsg("        You have no rights to access .");
//				System.out.println("no rights **********************************************************************");
//			}
			//***********************************************************************************************
			this.setMsg("                You have no rights to access ！");
			System.out.println("**********************************************************************\n\n\n");
			return ActionType.ACTION_NO_RIGHT;
		}*/
		System.out.println("hava rights **********************************************************************");
		String ret="list";
//		System.out.println(" \n\nActiong -------------->"+this.getClass().getName());
//		System.out.println(" cmd命令字 -------------->"+this.getCmd());
		try{
			if(this.getCmd()!=null){
				if(this.getCmd().equals(ActionType.ACTION_LIST)){
					ret = list();
				}
				else if(this.getCmd().equals(ActionType.ACTION_DATA_LIST)){
					ret = data();
				}
				else if(this.getCmd().equals(ActionType.ACTION_MAIN)){
					ret = mainList();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_ADD)){
					ret = goAdd();
				}
				else if(this.getCmd().equals(ActionType.ACTION_ADD)){
					ret = add();
				}
				else if(this.getCmd().equals(ActionType.ACTION_MSG_NOTIFY)){
					ret = msgNotify();
				}
				else if(this.getCmd().equals(ActionType.ACTION_DELETE)){
					ret = delete();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_UPDATE)){
					ret = goUpdate();
				}
				else if(this.getCmd().equals(ActionType.ACTION_UPDATE)){
					ret = update();
				} else if(this.getCmd().equals(ActionType.ACTION_GO_CHECK)){
					ret = goCheck();
				}else if(this.getCmd().equals(ActionType.ACTION_CHECK)){
					ret = check();
				}else if(this.getCmd().equals(ActionType.ACTION_CONDITION)){
					ret = condition();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_All_SEARCH)){
					ret = goAllSearch();
				}
				else if(this.getCmd().equals(ActionType.ACTION_ALL_SEARCH)){
					ret = allSearch();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_VIEW)){
					ret = goView();
				}
				else if(this.getCmd().equals(ActionType.ACTION_VIEW)){
					ret = view();
				}
				else if(this.getCmd().equals(ActionType.ACTION_SEARCH)){
					ret = search();
				}
				else if(this.getCmd().equals(ActionType.ACTION_DOWNLOAD)){
					ret = download();
				}
				else if(this.getCmd().equals(ActionType.ACTION_CHILD)){
					ret = child();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_DOWNLOAD)){
					ret = goDownload();
				}
				else if(this.getCmd().equals(ActionType.ACTION_ERROR)){
					ret = error();
				}
				else if(this.getCmd().equals(ActionType.ACTION_EXPORT)){
					ret = export();
				}
				else if(this.getCmd().equals(ActionType.ACTION_EXPORT_ALL)){
					ret = exportAll();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_TREE)){
					ret = goTree();
				}
				else if(this.getCmd().equals(ActionType.ACTION_LOGIN)){
					try{
						ret = login();
					}catch(Exception e){
						e.printStackTrace();
						this.getResponse().setCharacterEncoding("gbk");
						this.getResponse().getWriter().write(("登录失败，请重试。"));
						this.getResponse().getWriter().flush();
						this.getResponse().getWriter().close();
						return null;
//						this.setMsg("此操作无结果返回，请尝试修改查询条件等，然后再重试。");
//						return ActionType.ACTION_ERROR;
					}
				}
				else if(this.getCmd().equals(ActionType.ACTION_LOGOUT)){
					ret = logout();
				}
				else if(this.getCmd().equals(ActionType.ACTION_MSG)){
					ret = msg();
				}
				else if(this.getCmd().equals(ActionType.ACTION_OTHRE)){
					ret = other();
				}
				else if(this.getCmd().equals(ActionType.ACTION_PREVIEW)){
					ret = preview();
				}
				else if(this.getCmd().equals(ActionType.ACTION_PRINT)){
					ret = print();
				}
				else if(this.getCmd().equals(ActionType.ACTION_TREE)){
					ret = tree();
				}
				else if(this.getCmd().equals(ActionType.ACTION_UPLOAD)){
					ret = upload();
				}
				else if(this.getCmd().equals(ActionType.ACTION_MENU)){
					ret = menu();
				}
				else if(this.getCmd().equals(ActionType.ACTION_GO_BATCH_UPDATE_PERIOD)){
					ret = goBatchUpdatePeriod();
				}
				else if(this.getCmd().equals(ActionType.ACTION_BATCH_UPDATE_PERIOD)){
					ret = batchUpdatePeriod();
				}
				else if (this.getCmd().equals(ActionType.ACTION_CHANGE)){
					ret = change();
				}
				else if (this.getCmd().equals(ActionType.ACTION_GO_BATCH_ADD)){
					ret = goBatchAdd();
				}
				else if(this.getCmd().equals(ActionType.ACTION_BATCH_DATA_LIST)){
					ret = batchDataList();
				}
				else if(this.getCmd().equals(ActionType.ACTION_BATCH_ADD)){
					ret = batchAdd();
				}
				else if(this.getCmd().equals(ActionType.ACTION_BATCH_AD_DESC)){
					ret = goBatchSetAdDesc();
					
				}else if(this.getCmd().equals(ActionType.ACTION_BATCH_REMARK)){
					ret = goBatchRemark();
					
				}else if(this.getCmd().equals(ActionType.ACTION_BATCH_SETDATE)){
					ret = goBatchSetDate();
				}else if(this.getCmd().equals(ActionType.ACTION_GO_BATCH_CHECK)){
					ret = goBatchCheck();
				}
				else if(this.getCmd().equals(ActionType.ACTION_LOOK_CHECK_DATA)){
					ret = lookCheckData();
				}
				else if(this.getCmd().equals(ActionType.ACTION_LOOK_CHECK_INFO)){
					ret = lookCheckInfo();
				}
				else if(this.getCmd().equals(ActionType.ACTION_COPY)){
					ret = copy();
				}
				else if(this.getCmd().equals(ActionType.ACTION_DISABLE)){
					ret = disable();
				}
				else if(this.getCmd().equals(ActionType.ACTION_UPLOAD_BATCH)){
					ret = uploadBatch();
				}
				else if(this.getCmd().equals(ActionType.ACTION_LOGIC_DELETE)){
					ret = logicDelete();
				}else if(this.getCmd().equals(ActionType.ACTION_SHOW_BATCH_ADD_MSG)){
					ret = showBatchAddMsg();
				}else if(this.getCmd().equals(ActionType.ACTION_TREENODE_NAME)){
					setTreeNodeSession();
				}else{
					ret = ActionType.ACTION_ERROR;
				}
			}
			else{
				ret = ActionType.ACTION_ERROR;
			}
		}catch(Exception ex){
			ret = error(ex);
			ex.printStackTrace();
		}
		System.out.println("返回的结果页面：：：：：：" + ret);
		return ret;
	}
	
	public String showBatchAddMsg() {
		msg = (String)this.getSession().getAttribute("msg");
		formMap.put("vMap", this.getSession().getAttribute("vMap"));
		formMap.put("repeatKey", this.getSession().getAttribute("repeatKey"));
		data = (List)this.getSession().getAttribute("repeatData");
		this.getSession().removeAttribute("msg");
		this.getSession().removeAttribute("vMap");
		this.getSession().removeAttribute("repeatData");
		this.getSession().removeAttribute("repeatKey");
		return ActionType.ACTION_SHOW_BATCH_ADD_MSG;
	}

	public String logicDelete() {
		Object ids = this.getFormValue("ids");
		System.out.println("idslength============="+ids);
		if(ids!=null && ((String[])ids).length>0){
			if(bpo.logicDelete((java.io.Serializable[])ids)){
				this.msg = "{processId:\"1\",msg:\"删除成功\"}";
			}else{
				this.msg = "{processId:\"-1\",msg:\"删除失败\"}";
			}
		}else{
			this.msg = "{processId:\"-1\",msg:\"删除失败\"}";
		}
		return ActionType.ACTION_MSG;
	}

	public String list()
	{
		this.setFormData(bpo.listPage(pageForm.getPageNo(), pageForm.getPageSize()));
		return ActionType.ACTION_LIST;
	}
	public String data()
	{
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		if(user.getUserId().intValue()==1 || isPerm){
			this.setFormData(bpo.listPage(pageForm.getPageNo(), pageForm.getPageSize()));
		}else{
			String hql = "from "+obj.getClass().getName()+" obj where obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId  and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"'  and rsd.sentDepId="+user.getOrgId()+") ";
			this.setFormData(bpo.searchPage(hql, pageForm.getPageNo(), pageForm.getPageSize()));
		}
		return ActionType.ACTION_DATA_LIST;
	}
	public String mainList()
	{
		this.setFormValue("moduleCls", obj.getClass().getName());
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String clsName = obj.getClass().getSimpleName();
		if(user.getOrgId().intValue()==14 && clsName.equals("PatentApply")){
			clsName+=2;
		}
		String tempName = SysParametersUtil.getInstance().getValue(clsName);
		this.setFormValue("tempName", tempName);
		this.setFormValue("tempPath", SysParametersUtil.getInstance().getValue("TEMPLATE_PATH"));
		if(formMap.get("SEARCH_TYPE")!=null)
			return ActionType.ACTION_MAIN_HIST;
		else
			return ActionType.ACTION_MAIN;
	}
	
	/**
	 * 树节点名称存放到Session
	 */
	public void setTreeNodeSession() {
		
	}
	
	public String goAdd()
	{
		return ActionType.ACTION_GO_ADD;
	}
	
	public String goBatchAdd(){
		return ActionType.ACTION_GO_BATCH_ADD;
	}
	
	public String add()
	{
		boolean isSelfOrg = false;
		
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		if(obj.getClass()==Writings.class 
				|| obj.getClass() == STReport.class 
				|| obj.getClass()==TechnologyReport.class
				|| obj.getClass() == PublishPaper.class){
			isSelfOrg = true;
			ObjectUtil.setValue(obj, "setSentDepName", new Class[]{String.class}, new Object[]{user.getOrgname()});
		}
		Serializable id = bpo.save(obj);
		Method m = ObjectUtil.getMethod(obj.getClass(), "getSentDep", null);
		if(isSelfOrg){
				RecordSentDep rsd = new RecordSentDep();
				rsd.setSentDepId(user.getOrgId());
				rsd.setYyqTableName(bpo.getTableName(obj.getClass()));
				rsd.setSourceRecordId(Long.parseLong(id+""));
				bpo.save(rsd);
		}else if(m != null){
			Long objId = (Long)ObjectUtil.getValue(obj, "getId", null, null);
			String tableName = bpo.getTableName(obj.getClass());
			String v = (String)ObjectUtil.getValue(obj, "getSentDep", null, null);
			List sds = new ArrayList();
			processSentDep(sds, tableName, v, objId);
			if(sds.size()>0){
				Serializable[] ids = bpo.save(sds.toArray());
			}
		}
		if(id!=null){
			Object hasAccessoryObj = this.getFormValue("hasAccessory");
			if(hasAccessoryObj != null){
				String hasAccessory = ((String[])hasAccessoryObj)[0];
				if("YES".equalsIgnoreCase(hasAccessory)){
					this.setMsg("{processId:\"1\",sourceRecordId:\""+id+"\"}");
				}else{
					this.setMsg("{processId:\"1\",msg:\"保存成功\",sourceRecordId:\""+id+"\"}");
				}
			}else{
				this.setMsg("{processId:\"1\",msg:\"保存成功\",sourceRecordId:\""+id+"\"}");
			}
		}
		else{
			this.setMsg("{processId:\"-1\",msg:\"添加失败\"}");
		}
		return ActionType.ACTION_MSG;
	}
	
	public String msgNotify()
	{
		String msgNotify = (String)this.getSession().getAttribute(ActionType.ACTION_MSG_NOTIFY);
		if(msgNotify!=null && msgNotify.equals("true")){
			this.getSession().removeAttribute(ActionType.ACTION_MSG_NOTIFY);
			this.msg = (String)this.getSession().getAttribute("msg");
			this.getSession().removeAttribute("msg");
		}else if(msgNotify!=null && msgNotify.equals("false")){
			this.msg = "{processId:\"-2\",msg:\"正在保存数据!\"}";
		}else{
			this.msg = "{processId:\"-2\",msg:\"正在保存数据!\"}";
		}
		return ActionType.ACTION_MSG;
	}
	
	
	public String delete()
	{
		Object ids = this.getFormValue("ids");
		System.out.println("idslength============="+ids);
		if(ids!=null && ((String[])ids).length>0){
			Object flagObj = this.getFormValue("flag");
			if(flagObj != null && ((String[])flagObj).length>0 && "accessory".equals(((String[])flagObj)[0])){
				String accessorPath = SysParametersUtil.getInstance().getValue("ACCESSORY_PATH");
				bpo.setCls(Accessory.class);
				if(bpo.delete((java.io.Serializable[])ids)){
					String attachmentName = ((String[])this.getFormValue("attachmentName"))[0];
					File file = new File(accessorPath+File.separator+attachmentName);
					if(file.exists()){
						file.delete();
					}
					this.msg = "{processId:\"1\",msg:\"删除成功\"}";
				}else{
					this.msg = "{processId:\"-1\",msg:\"删除失败\"}";
				}
			}else{
				if(bpo.delete((java.io.Serializable[])ids)){
					this.msg = "{processId:\"1\",msg:\"删除成功\"}";
				}else{
					this.msg = "{processId:\"-1\",msg:\"删除失败\"}";
				}
			}
		}else{
			this.msg = "{processId:\"-1\",msg:\"删除失败\"}";
		}
		return ActionType.ACTION_MSG;
	}
	
	public String goUpdate()
	{
		String pkId = bpo.getSessionFactory().getClassMetadata(obj.getClass()).getIdentifierPropertyName();
		Method meth;
		java.io.Serializable value=null;
		try {
			meth = obj.getClass().getMethod("get"+pkId.substring(0, 1).toUpperCase()+pkId.substring(1), null);
			value = (java.io.Serializable)meth.invoke(obj, null);
		} catch (Exception e){}
		this.setObj(bpo.findByPk(value));
		String[] updateSentDep = (String[])this.getFormValue("updateSentDep");
		if(updateSentDep == null || !"NO".equalsIgnoreCase(updateSentDep[0])){
			Method m = ObjectUtil.getMethod(obj.getClass(), "setSentDep", new Class[]{String.class});
			if(m != null){
				String hql = "from RecordSentDep where sourceRecordID="+value+" and yyqTableName='"+bpo.getTableName(obj.getClass())+"'";;
				String sentDepId = "";
				List list = bpo.search(hql);
				if(list != null && list.size()>0){
					for(int i=0;i<list.size()-1;i++){
						sentDepId += ((RecordSentDep)list.get(i)).getSentDepId()+",";
					}
					sentDepId += ((RecordSentDep)list.get(list.size()-1)).getSentDepId();
					ObjectUtil.setValue(obj, m, new String[]{sentDepId});
				}
			}
		}
		
		return ActionType.ACTION_GO_UPDATE;
	}
	
	public String view(){
		return ActionType.ACTION_VIEW;
	}
	
	public String goView()
	{
		String pkId = bpo.getSessionFactory().getClassMetadata(obj.getClass()).getIdentifierPropertyName();
		Method meth;
		java.io.Serializable value=null;
		try {
			meth = obj.getClass().getMethod("get"+pkId.substring(0, 1).toUpperCase()+pkId.substring(1), null);
			value = (java.io.Serializable)meth.invoke(obj, null);
		} catch (Exception e) {}
		this.setObj(bpo.findByPk(value));
		String tableName = bpo.getTableName(obj.getClass());
		String hql = "from Accessory where sourceRecordId = "+value +" and yyqTableName='"+tableName+"'";
		data = bpo.search(hql);
		return ActionType.ACTION_VIEW;
	}
	
	public String update()
	{
		boolean bool = false;
		Object flagObj = this.getFormValue("flag");
		if(flagObj != null && ((String[])flagObj).length>0 && "accessory".equals(((String[])flagObj)[0])){
			String[] strs = (String[])this.getFormValue("sourceRecordId");
			String hql = "from Accessory where sourceRecordId="+strs[0]+" and yyqTableName='"+bpo.getTableName(obj.getClass())+"'";
			this.setData(bpo.search(hql));
			return ActionType.ACTION_LIST;
		}else{
			if(obj!=null){
				bool = bpo.update(obj);
				this.setFormValue("updateFlag", "TRUE");
			}else{
				this.setFormValue("updateFlag", "FALSE");
			}
			String[] updateSentDep = (String[])this.getFormValue("updateSentDep");
			if(bool){
				if(updateSentDep == null || !"NO".equalsIgnoreCase(updateSentDep[0])){
					Method m = ObjectUtil.getMethod(obj.getClass(), "getSentDep", null);
					if(m != null){
						Long objId = (Long)ObjectUtil.getValue(obj, "getId", null, null);
						String tableName = bpo.getTableName(obj.getClass());
						bool = bpo.execHql("delete from RecordSentDep where sourceRecordId="+objId+" and yyqTableName='"+tableName+"'");
						if(bool){
							String v = (String)ObjectUtil.getValue(obj, "getSentDep", null, null);
							List sds = new ArrayList();
							processSentDep(sds, tableName, v, objId);
							if(sds.size()>0){
								Serializable[] ids = bpo.save(sds.toArray());
								if(ids != null){
									this.msg = "{processId:\"1\",msg:\"更新成功\"}";
								}else{
									this.msg = "{processId:\"1\",msg:\"更新数据成功,报送单位失败\"}";
								}
							}else{
								this.msg = "{processId:\"1\",msg:\"更新成功\"}";
							}
						}else{
							this.msg = "{processId:\"1\",msg:\"更新数据成功,报送单位失败\"}";
						}
					}else{
						this.msg = "{processId:\"1\",msg:\"更新成功\"}";
					}
				} else{
					this.msg = "{processId:\"1\",msg:\"更新成功\"}";
				}
			}
			else{
				this.msg = "{processId:\"-1\",msg:\"更新失败\"}";
			}
			return ActionType.ACTION_MSG;
		}
	}
	
	public String search()
	{
		String searchProperty = ((String[])this.getFormValue("searchProperty"))[0];
		String searchKey = ((String[])this.getFormValue("searchKey"))[0];
		String orderStr = "";
		if(bpo.getOrderByDescStr() != null){
			orderStr = bpo.getOrderByDescStr();
		}
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			if("sentDep".equals(searchProperty)){
				hql = "select distinct obj from "+obj.getClass().getName()+" obj,RecordSentDep rsd,SysDepts d where " +
					  " obj.id=rsd.sourceRecordId and rsd.sentDepId=d.id and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"' and d.deptCname like '%"+searchKey+"%' "+orderStr;
			}else{
				hql = "from "+obj.getClass().getName()+" obj where obj."+searchProperty+" like '%"+searchKey+"%' "+orderStr;
			}
		}else{
			hql = "from "+obj.getClass().getName()+" obj where (obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId  and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"'  and rsd.sentDepId="+user.getOrgId()+"))  and obj."+searchProperty+" like '%"+searchKey+"%' "+orderStr;
		}
		this.setFormData(bpo.searchPage(hql, this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		//data = bpo.search(hql);
		return ActionType.ACTION_DATA_LIST;
	}
	
	public String goAllSearch()
	{
		this.setFormValue("moduleCls", obj.getClass().getName());
		this.setFormValue("tempName", SysParametersUtil.getInstance().getValue(obj.getClass().getSimpleName()));
		this.setFormValue("tempPath", SysParametersUtil.getInstance().getValue("TEMPLATE_PATH"));
		return ActionType.ACTION_GO_All_SEARCH;
	}
	
	public String allSearch()
	{
		return ActionType.ACTION_DATA_LIST;
	}
	
	protected boolean isGlobalPermissions(String moduleName){
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		if(user.getUserId().intValue()==1){
			return true;
		}
		if(moduleName == null)
		moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_PRINT);
		if(isPerm){
			return true;
		}
		return false;
	}
	
	protected boolean isSentDepRight(String moduleName){
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		if(user.getUserId().intValue()==1){
			return true;
		}
		if(moduleName == null)
			moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPrint = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_PRINT);
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		if(obj.getClass() == TechnologyReport.class ||
				obj.getClass() == STReport.class ||
				obj.getClass() == ReportIntroduce.class){
			return isPrint;
		}else{
			return isPrint || isPerm;
		}
	}
	
	public String child()
	{
		String sql = "from "+obj.getClass().getName() +" where ";
		Method[] methods = obj.getClass().getDeclaredMethods();
		int count = 0;
		for(int i=0; i<methods.length; ++i){
			Method m = methods[i];
			if(m.getName().startsWith("get")){
				String name = m.getName().substring(3);
				name = name.substring(0,1).toLowerCase()+name.substring(1);
				String retType = m.getReturnType().getName();
				try {
					Object value = m.invoke(obj, null);
					if(value!=null){
						++count;
						if(count>1)
							sql +=" and ";
						if(retType.indexOf("Long")>0 || retType.indexOf("Integer")>0){
							sql += name+"="+value;
						}else{
							sql += name+" ='"+value+"'";						
						}
					}
				} catch (Exception e) {}
			}
		}
		this.setFormData(bpo.searchPage(sql, this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		return ActionType.ACTION_MAIN;
	}
	public String goDownload()
	{
		return ActionType.ACTION_GO_DOWNLOAD;
	}
	
	public String goCheck(){
		this.goUpdate();
		return ActionType.ACTION_GO_CHECK;
	}
	
	public String goBatchCheck(){
		
		return ActionType.ACTION_GO_BATCH_CHECK;
	}
	
	public String check(){
		Object sts = null; 
		try {
			Method m = obj.getClass().getMethod("getSts", new Class[]{});
			sts = m.invoke(obj, new Object[]{});
		} catch (Exception e) {e.printStackTrace();}
		System.out.println(obj +" ---------------- "+sts);
		this.goUpdate();
		try {
			Method m = obj.getClass().getMethod("setSts", new Class[]{String.class});
			sts = m.invoke(obj, new Object[]{sts});
		} catch (Exception e) {e.printStackTrace();}
		System.out.println(sts);
		boolean bool = false;
		if(obj!=null)
			bool = bpo.update(obj);
		if(bool){
			this.msg = "{processId:\"1\",msg:\"审核成功\"}";
		}
		else{
			this.msg = "{processId:\"1\",msg:\"审核失败\"}";
		}
		return ActionType.ACTION_MSG;
	}
/*	public String check(){
		return ActionType.ACTION_CHECK;
	}*/
	public String condition(){
		return ActionType.ACTION_CONDITION;
	}
	
	public String download()
	{
		String[] paths = (String[])this.getFormValue("path");
		String path = paths[0];
		String[] attachmentNames = (String[])this.getFormValue("attachmentName");
		String attachmentName = attachmentNames[0];
		String[] showNames = (String[])this.getFormValue("showName");
		String showName = showNames[0];
		FileDownloadHandle.downloadFile(path, showName, attachmentName, this.getResponse());
		return null;
	}
	
	public String upload()
	{
		Object sourceRecordIdObj = this.getFormValue("sourceRecordId");
		if(accessory != null && sourceRecordIdObj != null){
			String sourceRecordIdStr = ((String[])sourceRecordIdObj)[0];
			System.out.println(sourceRecordIdStr);
			String accessorPath = SysParametersUtil.getInstance().getValue("ACCESSORY_PATH");
			FileUploadHandle fuh = new FileUploadHandle();
			fuh.setUploadDir(accessorPath);
			FileBean filebean = fuh.handleUploadFile(accessory, accessoryFileName, "", -1L);
			Accessory a = new Accessory();
			a.setAttachmentName(filebean.getNewName());
			a.setPath(filebean.getUrl());
			a.setFileSize(filebean.getSize());
			a.setSourceRecordId(Long.parseLong(sourceRecordIdStr));
			a.setYyqTableName(bpo.getTableName(obj.getClass()));
			a.setShowName(accessoryFileName);
			Serializable aid = bpo.save(a);
			if(aid==null){
				this.setMsg("{processId:\"-1\",msg:\"上传附件失败\"}");
			}else{
				this.setMsg("{processId:\"1\",msg:\"上传附件成功\"}");
			}
		} else if(addaccessory != null && sourceRecordIdObj != null){

			String sourceRecordIdStr = ((String[])sourceRecordIdObj)[0];
			System.out.println(sourceRecordIdStr);
			String accessorPath = SysParametersUtil.getInstance().getValue("ACCESSORY_PATH");
			FileUploadHandle fuh = new FileUploadHandle();
			fuh.setUploadDir(accessorPath);
			FileBean filebean = fuh.handleUploadFile(addaccessory, accessoryFileName, "", -1L);
			Accessory a = new Accessory();
			a.setAttachmentName(filebean.getNewName());
			a.setPath(filebean.getUrl());
			a.setFileSize(filebean.getSize());
			a.setSourceRecordId(Long.parseLong(sourceRecordIdStr));
			a.setYyqTableName(bpo.getTableName(obj.getClass()));
			a.setShowName(accessoryFileName);
			Serializable aid = bpo.save(a);
			if(aid==null){
				this.setMsg("{processId:\"-1\",msg:\"上传附件失败\"}");
			}else{
				this.setMsg("{processId:\"1\",msg:\"上传附件成功\"}");
			}
		
			
		}
		return ActionType.ACTION_MSG;
	}
	
	public String goTree() 
	{
		return ActionType.ACTION_GO_TREE;
	}
	
	public String tree()
	{
		return ActionType.ACTION_TREE;
	}
	
	public String export()
	{
		return ActionType.ACTION_EXPORT;
	}
	
	public String exportAll()
	{
		String order = ((String[])this.getFormValue("order"))[0].trim();
		String hql = getExportHql(order);
		List list = bpo.search(hql);
		List datas = new ArrayList();
		processExportObj(order, list, datas);
		Map beans = new HashMap();
		beans.put("datas", datas);
		beans.put("isGlobal", isSentDepRight(null));
		exportXls(beans,getExportFileName(),null);
		return null;
	}

	private String getExportFileName(){
		String fileName = "";
		if(obj.getClass()==STApply.class){
			fileName = "科技进步奖励申报批量导出";
		}else if(obj.getClass()==STPaper.class){
			fileName = "科技进步项目获奖批量导出";
		}else if(obj.getClass()==STReport.class){
			fileName = "科技进步科研报告批量导出";
		}else if(obj.getClass()==TechnologyApply.class){
			fileName = "技术总结奖励申报批量导出";
		}else if(obj.getClass()==TechnologyPaper.class){
			fileName = "技术总结项目获奖批量导出";
		}else if(obj.getClass()==TechnologyReport.class){
			fileName = "技术总结报告批量导出";
		}
		else{
			fileName = SysParametersUtil.getInstance().getValue(obj.getClass().getSimpleName());
			if(fileName != null && !"".equals(fileName.trim())){
				int pos = fileName.indexOf("模板");
				if(pos != -1){
					fileName = fileName.substring(0,pos)+"批量导出数据";
				}else{
					pos = fileName.indexOf(".");
					if(pos != -1){
						fileName = fileName.substring(0, pos) + "批量导出数据";
					}else{
						fileName = fileName + "批量导出数据";
					}
				}
			}else{
				fileName = null;
			}
		}
		return fileName;
	}
	
	private void processExportObj(String order, List list,List datas) {
		String orderMethodName = "get"+order.substring(0, 1).toUpperCase()+order.substring(1);
		Method orderMethod = ObjectUtil.getMethod(obj.getClass(), orderMethodName, null);
		String temp = "";
		ExcelBean eb = null;
		Map<String,ValidateVo> vMap = ValidateUtil.getInstance().getValidatesByClassName(obj.getClass().getName());
		 List<MethodBean> selectDDNames = getSelectDDName(vMap,obj.getClass());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		 for(int i=0;i<list.size();i++){
			Object obj = list.get(i);
			try {
				Object orderObj = orderMethod.invoke(obj, null);
				if(orderObj != null){
					String orderValue = "";
					if(orderObj instanceof String){
						orderValue = (String)orderObj;
					}else if(orderObj instanceof Date){
						orderValue = sdf.format((Date)orderObj);
					}
					if(!temp.equals(orderValue)){
						temp = orderValue;
						if(eb != null){
							datas.add(eb);
						}
						eb = new ExcelBean(orderValue);
					}
					for(int j=0;j<selectDDNames.size();j++){
						MethodBean mb = selectDDNames.get(j);
						Object gValue = mb.getGMethod().invoke(obj, null);
						if(gValue != null){
							String value = gValue.toString();
							for(int k=0;k<mb.getDd().size();k++){
								DataDictionary dd = mb.getDd().get(k);
								if(dd.getValue().equals(value)){
									mb.getSMethod().invoke(obj, getObjectByType(dd.getText(),mb.getType(),mb.getDateFormat()));
								}
							}
						}
					}
					eb.getData().add(obj);
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			if(i == list.size()-1){
				datas.add(eb);
			}
		}
	}
	
	public Object getObjectByType(String value,String type,String dateFormat){
		Object obj = null;
		if("STR".equals(type)){
			obj = value;
		}else if("INT".equals(type)){
			obj = Integer.valueOf(value);
		}else if("LONG".equals(type)){
			obj = Long.valueOf(value);
		}else if("FLT".equals(type)){
			obj = Float.valueOf(value);
		}else if("DATE".equals(type)){
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			try {
				obj = sdf.parse(value);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	private List<MethodBean> getSelectDDName(Map<String, ValidateVo> map,Class cls) {
		Set<Entry<String, ValidateVo>> set = map.entrySet();
		List<MethodBean> list = new ArrayList<MethodBean>();
		for (Entry<String, ValidateVo> entry : set) {
			if(!entry.getValue().isSentDep() 
					&& entry.getValue().getDd() != null 
					&& entry.getValue().getDd().size()>0){
				MethodBean mb = new MethodBean();
				String name = entry.getValue().getName();
				String getName = "get"+name.substring(0, 1).toUpperCase()+name.substring(1);
				String setName = "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
				Method gMethod = ObjectUtil.getMethod(cls, getName, null);
				Class type = getClassByType(entry.getValue().getType());
				Method sMethod = null;
				if(type != null){
					sMethod = ObjectUtil.getMethod(cls, setName, new Class[]{type});
				}
				mb.setName(name);
				mb.setType(entry.getValue().getType());
				mb.setDd(entry.getValue().getDd());
				mb.setDateFormat(entry.getValue().getDateFormat());
				mb.setGMethod(gMethod);
				mb.setSMethod(sMethod);
				list.add(mb);
			}
		}
		return list;
	}

	protected Class getClassByType(String name){
		Class cls = null;
		if("INT".equals(name)){
			cls = Integer.class;
		}else if("LONG".equals(name)){
			cls = Long.class;
		}else if("DATE".equals(name)){
			cls = Date.class;
		}else if("STR".equals(name)){
			cls = String.class;
		}else if("FLT".equals(name)){
			cls = Float.class;
		}
		return cls;
	}
	
	protected String getExportHql(String order) {
		String[] searchProperty = (String[])this.getFormValue("searchProperty");
		String[] searchKey = (String[])this.getFormValue("searchKey");
		String hql = "";
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		
		if(searchProperty != null && searchKey != null){
			if(user.getUserId().intValue()==1 || isPerm){
				if("sentDep".equals(searchProperty[0])){
					hql = "select distinct obj from "+obj.getClass().getName()+" obj,RecordSentDep rsd,SysDepts d where " +
						  " obj.id=rsd.sourceRecordId and rsd.sentDepId=d.id " +
						  "and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"' " +
						  "and d.deptCname like '%"+searchKey[0]+"%' order by obj."+order+" desc";
				}else{
					hql = "from "+obj.getClass().getName()+" obj where obj."+searchProperty[0]+" like '%"+searchKey[0]+"%' order by obj."+order+" desc";
				}
			}else{
				hql = "from "+obj.getClass().getName()+" obj " +
						"where (obj.maintainDep="+user.getOrgId()+" or " +
								"EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId  " +
								"and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"'  " +
								"and rsd.sentDepId="+user.getOrgId()+"))  " +
								"and obj."+searchProperty[0]+" like '%"+searchKey[0]+"%' order by obj."+order+" desc";
			}
		}else{
			if(user.getUserId().intValue()==1 || isPerm){
				hql = "from "+obj.getClass().getName()+" order by "+order+" desc";
			}else{
				hql = "from "+obj.getClass().getName()+" obj where obj.maintainDep="+user.getOrgId()+" or" +
						" EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId " +
						"and rsd.yyqTableName='"+bpo.getTableName(obj.getClass())+"' " +
								"and rsd.sentDepId="+user.getOrgId()+") order by obj."+order+" desc";
			}
		}
		return hql;
	}

	protected void exportXls(Map beans,String targetFileName,String templateName) {
		 LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		 HttpServletResponse response = this.getResponse();
	     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		 try{	
			 	if(targetFileName==null){
			 		targetFileName = sdf.format(new Date());
			 	}
				XLSTransformer transformer = new XLSTransformer();
				String fn = obj.getClass().getName();
				if(user.getUserId().intValue()==14 && "com.yyq.adms.yyb.patent.pojo.PatentApply".equals(fn)){
					fn+=2;
				}
				String fileName = fn+".xls";
				if(templateName != null){
					fileName = templateName;
				}
				String path = this.getSession().getServletContext().getRealPath("/excelTemplate/"+fileName);
				Workbook book = transformer.transformXLS(new FileInputStream(new File(path)), beans);
				transformer.groupCollection("datas.data");
				response.reset();
		        response.setContentType("application/x-msdownload;charset=UTF-8");
		     	response.setCharacterEncoding("UTF-8");
		     	response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName,"UTF-8") + ".xls");
		     	book.write(response.getOutputStream());
		 }catch(Exception e){
		    	e.printStackTrace();
	     }finally{
	    	 try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		 }
	}
	
	public String error(){
		return ActionType.ACTION_ERROR;
	}
	
	public String error(Exception e)
	{
//		this.setMsg("后台出错拉,可能是操作失误,具体错误原因:"+e.toString());
//		this.setMsg("此操作无结果返回，请尝试修改查询条件等，然后再重试。");
		this.setMsg("系统繁忙，请重试。");
		return ActionType.ACTION_ERROR;
	}
	
	public String login()
	{
		return ActionType.ACTION_LOGIN;
	}
	
	public String logout()
	{
		return ActionType.ACTION_LOGOUT;
	}
	
	public String msg()
	{
		this.msg = "{processId:\"1\",msg:\"OK\"}";
		
		return ActionType.ACTION_MSG;
	}
	
	public List pressData(List dataList,String[] dataType,String[] dataMeta,Class cls) {
		List list = new ArrayList();
		try{
			for(int i=0;i<dataList.size();i++){
				Object[] obj = (Object[]) dataList.get(i);
				Object vo = Class.forName(cls.getName()).newInstance();
				int len = 0;
				//这里无法跨数据库，必须判断一下，如果是SQL Server，len需设置为1(DB2因为有，所以必须要少一个，len设置为0才对)
				
				len = 0; //这里与admsPrint中不同，mssql时设置len为1反而会出现错位，暂设为0。DB2与Oracle时需再验证一下
				
				for(int j=0;j<obj.length;j++){
					if(j>dataType.length)
						continue;
					String colType = dataType[j];
					String name = dataMeta[j];
					Object value = obj[j];
//					System.out.println(j+" = "+colType+"  -----  "+name+"  -------  "+value);
					if(colType.equals("STR")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{String.class});
						m.invoke(vo, new Object[]{null==value? null:String.valueOf(value)});
					}else if(colType.equals("INT") ){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Integer.class});
						m.invoke(vo, new Object[]{null==value?null:Integer.valueOf(String.valueOf(value))});
					}else if(colType.equals("LONG")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Long.class});
						if(value!=null && !String.valueOf(value).equals(""))
							m.invoke(vo, new Object[]{Long.valueOf(String.valueOf(value))});
					}else if(colType.equals("SHT")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Short.class});
						m.invoke(vo, new Object[]{null==value? null:Short.valueOf(String.valueOf(value))});
					}else if(colType.equals("FLT")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Float.class});
						m.invoke(vo, new Object[]{null==value? null:Float.valueOf(String.valueOf(value))});
					}else if(colType.equals("DATE")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Date.class});
						m.invoke(vo, new Object[]{null==value? null:value});
					}else if(colType.equals("TIME")){
						Method m = vo.getClass().getMethod("set"+name, new Class[]{Date.class});
						m.invoke(vo, new Object[]{null==value? null:value});
					}
				}
				list.add(vo);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return list;
	}
	
	public String other()
	{
		return ActionType.ACTION_OTHRE;
	}
	
	public String copy()
	{
		return ActionType.ACTION_COPY;
	}
	
	public String disable(){
		return ActionType.ACTION_MSG;
	}
	
	public String print()
	{
		return ActionType.ACTION_PRINT;
	}
	
	public String preview()
	{
		return ActionType.ACTION_PREVIEW;
	}
	
	public String menu(){
		return ActionType.ACTION_MENU;
	}
	
	public void beginRequest(){
		this.getSession().setAttribute(ActionType.ACTION_MSG_NOTIFY, "false");
	}
	public void endRequest(String msg){
		this.getSession().setAttribute(ActionType.ACTION_MSG_NOTIFY, "true");
		this.getSession().setAttribute("msg", msg);
	}
	
	/**
	 * 获取request;
	 * 
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request;
	}
	
	/**
	 * 获取response;
	 * 
	 */
	public HttpServletResponse getResponse() {
		HttpServletResponse response = ServletActionContext.getResponse();
		return response;
	}
	
	/**
	 * 获取session;
	 */
	public HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		return session;
	}
	
	/**
	 * 取得上下文路径
	 * @return
	 */
	public String getContextPath()
	{	
		return 	getRequest().getContextPath();
	}
	
	/**
	 * 取得上下文路径
	 * @return
	 */
	public String getRealPath()
	{	
		return 	getServletContext().getRealPath("");
	}
	
	/**
	 * 取得servlet上下文
	 * @return
	 */
	public ServletContext getServletContext()
	{
		return ServletActionContext.getServletContext();
	}
	
	public String getMsg()
	{
		return msg;
	}

	public void setMsg(String msg)
	{
		this.msg = msg;
	}

	public String getCmd()
	{
		return cmd;
	}

	public void setCmd(String cmd)
	{
		this.cmd = cmd;
	}

	public Map getFormMap()
	{
		return formMap;
	}

	public void setFormMap(Map formMap)
	{
		this.formMap = formMap;
	}
	
	public void setFormValue(String key, Object value)
    {
    	formMap.put(key, value);
    }

    public Object getFormValue(String key)
    {
        return formMap.get(key);
    }
	
	public String getProcessId()
	{
		return processId;
	}

	public void setProcessId(String processId)
	{
		this.processId = processId;
	}


	public BaseBpo getBpo()
	{
		return bpo;
	}


	public void setBpo(BaseBpo bpo)
	{
		this.bpo = bpo;
	}

	public PageFormData getFormData()
	{
		return formData;
	}


	public void setFormData(PageFormData formData)
	{
		this.formData = formData;
		this.setPageForm(this.formData.getPageForm());
		this.setData(this.formData.getData());
	}


	public List getData()
	{
		return data;
	}


	public void setData(List data)
	{
		this.data = data;
	}


	public PageForm getPageForm()
	{
		return pageForm;
	}


	public void setPageForm(PageForm pageForm)
	{
		this.pageForm = pageForm;
	}


	public Object getObj()
	{
		return obj;
	}


	public void setObj(Object obj)
	{
		this.obj = obj;
	}

	public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}
	
	public String goBatchUpdatePeriod(){
		return ActionType.ACTION_GO_BATCH_UPDATE_PERIOD;
	}
	
	public String batchUpdatePeriod(){
		return ActionType.ACTION_BATCH_UPDATE_PERIOD;
	}
	
	public String change(){
		this.getRequest().getSession().setAttribute("pageSize", this.getPageForm().getPageSize());
		return null;
	}
	
	public String uploadBatch(){
		return ActionType.ACTION_UPLOAD_BATCH;
	}
	
	public String batchDataList(){
		return ActionType.ACTION_BATCH_DATA_LIST;
	}
	
	
	public List processBatchAddParent(List list) {
		return list;
	}
	
	public String batchAdd(){
		if(accessory != null){
			if("xls".equals(accessoryFileName.substring(accessoryFileName.lastIndexOf(".")+1))){
				Map<String,ValidateVo> vMap = ValidateUtil.getInstance().getValidatesByClassName(obj.getClass().getName());
				List<Map<String, JxlsVo>> data = JxlsUtil.getInstance().transfromData(accessory);
				List list = new ArrayList();
				List<Map<String, JxlsVo>> otherOrgRepeatData = new ArrayList<Map<String, JxlsVo>>(); 
				LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
				try {
					StringBuffer[] errMsg = JxlsUtil.getInstance().validateXls
					(data, vMap, obj.getClass(), list,user,otherOrgRepeatData);
					msg = errMsg[0].toString();
					int repeatDBSize = otherOrgRepeatData.size();
					if("".equals(msg) && otherOrgRepeatData.size() == 0){
						if(list.size()>0){
							if(isNeedBatchAddParent == true) {
								list = processBatchAddParent(list);
							}
							
							Serializable[] ids = bpo.save(list.toArray());
							if(ids != null){
								Method idM = ObjectUtil.getMethod(obj.getClass(), "getId", null);
								if(obj.getClass()==Writings.class 
										|| obj.getClass() == STReport.class 
										|| obj.getClass()==TechnologyReport.class
										|| obj.getClass() == PublishPaper.class ){
										List sds = new ArrayList();
										for(int i=0;i<list.size();i++){
											Object o = list.get(i);
											Object objId = idM.invoke(o, null);
											RecordSentDep rsd = new RecordSentDep();
											rsd.setSentDepId(user.getOrgId());
											rsd.setYyqTableName(bpo.getTableName(obj.getClass()));
											rsd.setSourceRecordId(Long.parseLong(objId+""));
											sds.add(rsd);
										}
										if(sds.size()>0){
											ids = bpo.save(sds.toArray());
											if(ids != null){
												getBatchMsg(data, list,otherOrgRepeatData,repeatDBSize);
											}else{
												msg = "批量导入成功,报送单位添加失败";
											}
										}else{
											getBatchMsg(data, list,otherOrgRepeatData,repeatDBSize);
										}
								}else{
									Method m = ObjectUtil.getMethod(obj.getClass(), "getSentDep", null);
									if(m != null){
										List sds = new ArrayList();
										String tableName = bpo.getTableName(obj.getClass());
										for(int i=0;i<list.size();i++){
											Object o = list.get(i);
											String v = (String)m.invoke(o, null);
											Object objId = idM.invoke(o, null);
											processSentDep(sds, tableName, v, objId);
										}
										if(sds.size()>0){
											ids = bpo.save(sds.toArray());
											if(ids != null){
												getBatchMsg(data, list,otherOrgRepeatData,repeatDBSize);
											}else{
												msg = "批量导入成功,报送单位添加失败";
											}
										}else{
											getBatchMsg(data, list,otherOrgRepeatData,repeatDBSize);
										}
									}else{
										getBatchMsg(data, list,otherOrgRepeatData,repeatDBSize);
									}
								}
							}else{
								msg = "批量导入失败！";
							}
						}else{
							if(repeatDBSize>1){
								msg = "总共有"+data.size()+"条记录,"+
								(repeatDBSize-1)+"条与数据库重复了,详细信息如下:<br/>"+otherOrgRepeatData.get(repeatDBSize-1).toString()+"保存进去0条!";
							}else{
								msg = "批量导入数据为空,请添加数据!";
							}
						}
						msg = "{processId:\"1\",msg:\""+msg+"\"}";
					}
					/*else if(!"".equals(errMsg[0].toString())){
						this.getSession().setAttribute("msg", errMsg[0].toString());
						msg = "{processId:\"2\",msg:\""+errMsg[0].toString()+"\"}";
					}else if(otherOrgRepeatData.size() > 0){
						this.getSession().setAttribute("vMap", vMap);
						this.getSession().setAttribute("repeatData", otherOrgRepeatData);
						msg = "{processId:\"3\",msg:\"数据重复!\",width:\""+vMap.size()+"\",height:\""+otherOrgRepeatData.size()+"\"}";
					}*/
					else{
						this.getSession().setAttribute("msg", errMsg[0].toString());
						this.getSession().setAttribute("vMap", vMap);
						this.getSession().setAttribute("repeatData", otherOrgRepeatData);
						this.getSession().setAttribute("repeatKey", errMsg[1].toString());
						msg = "{processId:\"3\",msg:\"数据重复!\",width:\""+vMap.size()+"\",height:\""+otherOrgRepeatData.size()+"\"}";
					}
				} catch (Exception e) {
					msg = "{processId:\"1\",msg:\"文件格式不正确,批量导入出错!\"}";
					e.printStackTrace();
				}
			}else{
				msg = "{processId:\"1\",msg:\"文件类型不支持!\"}";
			}
		}
		//return ActionType.ACTION_BATCH_ADD;
		return ActionType.ACTION_MSG;
	}

	protected void getBatchMsg(List<Map<String, JxlsVo>> data, List list,
			List otherOrgRepeatData, int repeatDBSize) {
		if(repeatDBSize>1){
			msg = "总共有"+data.size()+"条记录,"+
			(repeatDBSize-1)+"条与数据库重复了,详细信息如下:<br/>"+otherOrgRepeatData.get(repeatDBSize-1).toString()
			+"保存进去"+list.size()+"条!";
		}else{
			msg = "批量导入成功！";
		}
	}

	protected void processSentDep(List sds, String tableName, String v,
			Object objId) {
		if(v != null && !v.equals("")){
			String[] vs = v.split(",");
			for(int j=0;j<vs.length;j++){
				RecordSentDep rsd = new RecordSentDep();
				rsd.setSentDepId(Long.parseLong(vs[j]));
				rsd.setYyqTableName(tableName);
				rsd.setSourceRecordId(Long.parseLong(objId.toString()));
				sds.add(rsd);
			}
		}
	}
	
	public String goBatchSetAdDesc(){
		return ActionType.ACTION_BATCH_AD_DESC;
	}
	
	public String goBatchRemark(){
		return ActionType.ACTION_BATCH_REMARK;
	}
	
	public String goBatchSetDate(){
		return ActionType.ACTION_BATCH_SETDATE;
	}
	
	public String lookCheckData(){
		return ActionType.ACTION_LOOK_CHECK_DATA;
	}
	
	public String lookCheckInfo(){
		return ActionType.ACTION_LOOK_CHECK_INFO;
	}
	
	public String getPagePosition() {
		return pagePosition;
	}

	public void setPagePosition(String pagePosition) {
		this.pagePosition = pagePosition;
	}
	
	public long getTableId(){
		String hql = "select id from DeployTable where tableName='"+bpo.getTableName(obj.getClass())+"'";
		List list = bpo.search(hql);
		long id = (Long)(list.get(0));
		return id;
	}

	public File getAccessory() {
		return accessory;
	}

	public void setAccessory(File accessory) {
		this.accessory = accessory;
	}

	public String getAccessoryFileName() {
		return accessoryFileName;
	}

	public void setAccessoryFileName(String accessoryFileName) {
		this.accessoryFileName = accessoryFileName;
	}

	public String getAccessoryContentType() {
		return accessoryContentType;
	}

	public void setAccessoryContentType(String accessoryContentType) {
		this.accessoryContentType = accessoryContentType;
	}

}
